<?php

namespace app\common\service;

use app\data\util\HttpUtil;
use app\data\util\MqQueueName;
use app\order\logic\OrderShipLogic;
use app\order\logic\OrderWhLogic;
use app\order\model\SkuWeightSize;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Config;
use think\facade\Db;

class YiJTApiService
{
    protected $url = null;

    public function __construct()
    {
        $this->url = Config('Logisticskey.YiJT.url');
    }

    /**
     * @param $order
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @desc  生成订单
     */
    public function createOrder($order)
    {

        htmlLog(['order'=>$order],OPERATE_LOG . date('Ym') . '/createOrder/' . date('Ymd') . '.txt');
        $return = [
            'order_id'     => $order['order_id'],
            'shop_id'      => $order['shop_id'],
            'warehouse_id' => $order['warehouse_id'],
            'data'         => '',
            'return0'      => '',
            'return1'      => '',
        ];

        $JsonData = self::buildJsonData($order);
        $orderDetail_arr = [];
        $skuInfos   = Db::name('order_info')->where('order_id', $order['order_id'])->column('seller_sku');

        foreach($skuInfos as $v){
            $orderDetail_arr[] = get_seller_sku($v);
        }

        if(!$orderDetail_arr)  return true;

        //数组整合
        foreach($orderDetail_arr as $v){
            if(isset($v[0]) && is_array($v[0])){
                foreach($v as $value){
                    $arr[] = $value;
                }
            }else{
                $arr[] = $v;
            }
        }

        foreach($arr as $v){
            $sample_sku = self::get_sample_sku($v['sku']);
            $OrderDetail[] = [
                'sku'   => $sample_sku,
                'nums'=> $v['qtyOrdered'],
            ];
        }
        $OrderDetail                 = self::getQtyOrdered($OrderDetail);
        $JsonData["deliver_products"] = $OrderDetail;
        //手动选择渠道
        if(isset($order['golden_ant']) && $order['golden_ant'] != ''){
            $resDeliveryTxt  = self::getDeliveryTxt($order['golden_ant']);
            $JsonData["chqd"]  = $resDeliveryTxt;
        }

        $JsonDatas[] = $JsonData;
        //订单数据推送到易境通 2024-12-07
        $url = $this->url . Config('Logisticskey.YiJT.add_order');
        htmlLog(['url'=>$url,'params'=>$JsonDatas,'order_id'=>$order['order_id']],OPERATE_LOG . date('Ym') . '/createOrder/' . date('Ymd') . '.txt');
        $response = HttpUtil::postUrlYiJT($url, $JsonDatas);
        $result   = json_decode($response, true);
        htmlLog(['response'=>$result,'order_id'=>$order['order_id']],OPERATE_LOG . date('Ym') . '/createOrder/' . date('Ymd') . '.txt');
        //返回结果处理;
        if (isset($result['error']) && $result['error'] == "T") {
            self::handleSuccessShipping($response,$order,$JsonDatas);
        } else {
            self::handleFailedShipping($response,$order,$return);
        }
        return true;
    }


    /**
     * @desc  构建 JsonData返货参数处理
     * @date  2024-12-07
     * @author zhangheng
     */
    public function buildJsonData($order=[]){
        $JsonData = [];
        $JsonData['zip'] = $order['postal_code'];
        $JsonData['country'] = "美国";
        $JsonData['deliver_products'] = [];
        $JsonData['address'] = $order['address_detail'];
        $JsonData['city'] = $order['state'];
        $JsonData['district'] = $order['city'];
        $JsonData['deliver_no'] = $order['order_id'];
        $JsonData['mobile'] = $order['phone_number'];
        $JsonData['phone'] = $order['phone_number'];
        $JsonData['ck_nums'] = Config('Logisticskey.YiJT.ck_nums');
        $JsonData['token'] = Config('Logisticskey.YiJT.token');
        $JsonData['chqd'] = Config('Logisticskey.YiJT.chqd');
        $JsonData['contact'] = $order['name'];
        $JsonData['email'] = $order['buyer_email'];
        $JsonData['platform'] = "shopify";
        return $JsonData;
    }



    /**
     * @desc   匹配获取可以发货的库存数据
      * @date  2024-12-07
     * @author zhangheng
     * @title  尾部处理
     */
    public function get_sample_sku($sku=''){
        $sku_info = explode('-',$sku);
        $last     = $sku_info[2]??'';
        if($last=='XL/2XL'){
            $last = 'XL';
        }
        if($last=='3XL/4XL'){
            $last = '3XL';
        }

        if($last=='4XL/5XL'){
            $last = '4XL';
        }

        if($last=='5XL/6XL'){
            $last = '5XL';
        }

        if($last=='6XL/7XL'){
            $last = '6XL';
        }

        if($last=='XS/S'){
            $last = 'S';
        }
        if($last=='M/L'){
            $last = 'M';
        }
        return  $sku_info[0].'-'.$sku_info[1].'-'.$last;
    }


    /**
     * @desc 获取渠道
     * @date  2024-12-07
     * @author zhangheng
     */
    public function getDeliveryTxt($golden_ant=''){
        $arr = [
            'LA-DYY' => "LA-DYY",
            'TIK-shop' => "TIK-shop",
            '113-亚马逊自提' => "113-亚马逊自提",
            'HWC-TK(LBF)' => "HWC-TK(LBF)",
            'NY-A-亚马逊自提' => "NY-A-亚马逊自提",
            'CA-PM-DYY' => "CA-PM-DYY",
            'HWC-TK（LB）' => "HWC-TK（LB）",
            'HWC-TK(NYF)' => "HWC-TK(NYF)",
            'YMS-自提' => "YMS-自提",
            'USPS-JS' => "USPS-JS",
            'HWC-TK(NYA)' => "HWC-TK(NYA)",
            'HWC-TK（LBA）' => "HWC-TK（LBA）",
            'TIK-shop（NYA）' => "TIK-shop（NYA）",
            'USPS-CA-PY' => "USPS-CA-PY",
            'TEMU-shop' => "TEMU-shop",
            'TEMU-shop（NY）' => "TEMU-shop（NY）",
            'USPS-NY-PY' => "USPS-NY-PY",
            'HWC-TK(LBS)' => "HWC-TK(LBS)",
            'HWC-TK(LBAS)' => "HWC-TK(LBAS)",
            'TIK-shop(NY)' => "TIK-shop(NY)",
            'USPS-NY-JS' => "USPS-NY-JS",
            'UPS-JNA' => "UPS-JNA",
            '2030'    => "HWC-DLZ ",
            '2015'    => "HWC-DLZ ",
            '1003'    => "HWC-DLZ ",
        ];
        return $arr[$golden_ant]??'';
   }
    /**
     * @desc 处理发货成功的情况
    * @date  2024-12-07
     * @author zhangheng
     */
    private function handleSuccessShipping($response=[],$order=[],$JsonDatas=[])
    {

        $result            = json_decode($response, true);
        $tracking_number   = '';
        $return['code']    = 3;
        $return['msg']     = "回传物流单号";
        $return['return0'] = $response;
        $return['data']    = $tracking_number;
        //有跟踪号代表发货了
        $msg                            = '金蚁自发货，已发货';
        $status                         = 3;
        if($order['type'] == 2){ //金蚁走官方面单发货，已返回真实运单
            $return['msg']         = "强制金蚁发货成功，已回传面单，不继续进行后续操作";
            $return['return0']     = json_encode($JsonDatas);
            $msg                   = "发货成功，金蚁走官方面单发货,无需后续刷运单号";
            $status                = 5;
            $tracking_number       = Db::name('order')->where('order_id',$order['order_id'])->value('tracking_number');
        }
        $exist_ship = Db::name('order_ship')->where('order_id', $order['order_id'])->find();
        if(!$exist_ship){
            Db::name('order_ship')->where('order_id', $order['order_id'])->insert([
                    'order_id'        =>$order['order_id'],
                    'shop_id'         =>$order['shop_id'],
                    'warehouse_id'    =>$order['warehouse_id'],
                    'status'          =>$status,
                    'time'            =>time(),
                    'tracking_number' =>$tracking_number,
                    'msg'             =>$msg,
                    'type'            =>$order['type']
                ]
            );
        }else{
            Db::name('order_ship')->where('order_id', $order['order_id'])->update([
                    'status'           =>$status,
                    'time'             =>time(),
                    'warehouse_id'     =>$order['warehouse_id'],
                    'tracking_number'  =>$tracking_number,
                    'msg'              =>$msg,
                ]
            );
        }
        if($order['type'] == 1){ //金蚁自主发货
            Db::name('order')->where('order_id', $order['order_id'])->update([
                'tracking_number'=>$tracking_number
            ]);
        }

        Db::name('order')->where('order_id', $order['order_id'])->update([
            'send_status'=>1
        ]);

        OrderShipLogic::insertOrderShipLog($return);
    }

    /**
     * @desc 处理发货失败的情况
        * @date  2024-12-07
     * @author zhangheng
     */
    private function handleFailedShipping($response='',$order=[], $return=[])
    {
        $result               = json_decode($response, true);
        $return['code']       = 2;
        $return['msg']        = "错误：" . $result['content'];
        $return['return0']    = $response;
        $updateShip['status'] = 2;
        $updateShip['time']   = time();
        $updateShip['msg']    = $return['msg'];
        $updateShip['warehouse_id'] = $order['warehouse_id'];
        $exist_ship = Db::name('order_ship')->where('order_id',$order['order_id'])->find();
        if(!$exist_ship){
            Db::name('order_ship')->insert([
                'order_id'    =>$order['order_id'],
                'shop_id'     =>$order['shop_id'],
                'warehouse_id'=>$order['warehouse_id'],
                'status'      =>2,
                'time'        =>time(),
                'msg'         =>$response,
                'type'        =>$order['type'],
            ]);
        }else{
            Db::name('order_ship')->where('order_id', $order['order_id'])->update($updateShip);
        }

        Db::name('order')->where('order_id', $order['order_id'])->update([
            'send_status'=>2
        ]);
        OrderShipLogic::insertOrderShipLog($return);
    }

    
    /**
     * @desc 数据统计
     * @date 2024-02-22
     */
    public function getQtyOrdered($info)
    {
        $outputArray = [];
        foreach ($info as $item) {
            $sku = $item['sku'];
            if (isset($outputArray[$sku])) {
                $outputArray[$sku]['nums'] += $item['nums'];
            } else {
                $outputArray[$sku] = $item;
            }
        }
        return array_values($outputArray);
    }

    /**
     * @desc     易境通发货回传物流单号正常
     * @date     2024/12/07
     * @author   zhangheng
     */
    public function update_tracking_number()
    {
        //查询需要回传物流单号的订单 ,通过仓库编码更新
        $where[]  = ['ship_status', '=', 3];
        $where[]  = ['warehouse_id', '=', 6];
        $where[]  = ['tracking_number', '>', 0];
        $startOfDay = date('Y-m-d 00:00:00');
        $endOfDay   = date('Y-m-d 23:59:59');
        $where[]    = ['create_time', 'between', [$startOfDay,$endOfDay]];
        $where = [];
        $orders     = Db::name('order_shopify_list')->where($where)->order('create_time asc')->limit(500)->select()->toarray();
        // if(!$orders)    return '暂无数据!';
        $orders = objectToArray($orders);
        //通过查询的单号取接口数据循环更新
        foreach ($orders as $order) {
            $order['type']  = 1;
            //推动数据到队列;
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_JINYI_TRACKING_NUMBER_UPDATE_QUEUE,
                $order,
                false
            );
        }
        $num = count($orders);
        return '易境通处理数据'.$num.'条';
    }

    /**
     * @desc    易境通自发货物流单号回传mq消费方法
     * @date     2024/12/07
     * @author   zhangheng
     */
    public function tracking_number_update_consumer($order){ 
        $url = $this->url . Config('Logisticskey.YiJT.hwc_order');
        $JsonDatas = [
            'token' => Config('Logisticskey.YiJT.token'),
            'deliver_no' => $order['order_id'],
        ];
        $JsonDatas[] = $JsonDatas;
        $response = HttpUtil::postUrlYiJT($url, $JsonDatas);
        $result   = json_decode($response, true);
        halt($result);
        
        htmlLog(['params'=>$order,'response'=>$result],OPERATE_LOG . date('Ym') . '/tracking_number_update_consumer/' . date('Ymd') . '.txt');
        $Wt_LogisticsOrderNo    = $result['Data']['Wt_LogisticsOrderNo']??'';
        if(isset($result['Status']) && $result['Status']=='1000'){
            self::add_jin_yi_success_log($type,$order['order_id'],$Wt_LogisticsOrderNo,$shop_id,$order['warehouse_id']);
        }else{
            self::add_jin_yi_error_log($type,$result['Message'],$order['order_id'],$Wt_LogisticsOrderNo,$shop_id,$order['warehouse_id']);
        }
        return  true;
    }

    

    /**
     * @desc  记录易境通回传单号
     * @date     2024/12/07
     * @author   zhangheng
     */
    public function add_jin_yi_success_log($type='',$order_id='',$Wt_LogisticsOrderNo='',$shop_id='',$warehouse_id=''){
        $old_tracking  = Db::name('order_shopify_list')->where('order_id', $order_id)->find();
        htmlLog(['type'=>$type,'order_id'=>$order_id,'Wt_LogisticsOrderNo'=>$Wt_LogisticsOrderNo,'shop_id'=>$shop_id,'warehouse_id'=>$warehouse_id],OPERATE_LOG . date('Ym') . '/add_jin_yi_success_log/' . date('Ymd') . '.txt');
        if(preg_match("/^9\d{9,}$|^42\d{9,}$/", $Wt_LogisticsOrderNo)){
            $Message         = '易境通物流单号回传完成';
            $status          = 4;
            $tracking_number = $Wt_LogisticsOrderNo;
            $code            = 4;
            //更新订单主表
            Db::name('order_shopify_list')->where('order_id', $order_id)->update([
                'ship_status'         => $status,
                'tracking_number'     => $tracking_number,
                'msg'                 => $Message,
                'update_time'         =>date("Y-m-d H:i:s", time()),
            ]);

            //数据推送到队列处理,2024-07-12
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_TIK_TRACK_TO_SHOPIFY_QUEUE,
                [
                    'order_id'       =>$order_id,
                    'shop_id'        =>$shop_id,
                    'tracking_number'=>$tracking_number,
                ],
                false
            );
        }else{
            $Message = '物流单号生成中';
            Db::name('order_shopify_list')->where('order_id', $order_id)->update([
                'ship_status'         => 3,
                'tracking_number'     => $old_tracking['tracking_number']??'',
                'msg'                 => '物流单号生成中',
                'update_time'         =>date("Y-m-d H:i:s", time()),
            ]);
            }
            $return['code']   = 3;
            $return['shop_id']= $shop_id;
            $return['order_id'] = $order_id;
            $return['warehouse_id']= $warehouse_id;
            $return['msg']    = $Message;
            $return['data']   = $Wt_LogisticsOrderNo;
            OrderShipLogic::insertOrderShipLog($return);
            return  true;
    }

    

    /**
     * @desc  记录易境通回传单号
     * @date     2024/12/07
     * @author   zhangheng
     */
    public function add_jin_yi_error_log($type='',$Message='',$order_id='',$Wt_LogisticsOrderNo='',$shop_id='',$warehouse_id=''){
        Db::name('order_shopify_list')->where('order_id', $order_id)->update([
            'ship_status'      => 3,
            'msg'              => $Message,
            'update_time'      =>date("Y-m-d H:i:s", time()),
        ]);
        $return['code']            = 3;
        $return['shop_id']         = $shop_id;
        $return['order_id']        = $order_id;
        $return['warehouse_id']    = $warehouse_id;
        $return['msg']             = $Message;
        $return['data']            = $Wt_LogisticsOrderNo;
        OrderShipLogic::insertOrderShipLog($return);
        return  true;
    }
    
}
